package com.ff.sca.user.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ff.sca.common.constant.Constant;
import com.ff.sca.common.entity.ztree.UserNode;
import com.ff.sca.common.util.CharUtil;
import com.ff.sca.user.entity.KvmUser;
import com.ff.sca.user.dao.KvmUserDao;
import com.ff.sca.user.service.IKvmUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author gw123
 * @since 2018-11-16
 */
@Service
public class KvmUserServiceImpl extends ServiceImpl<KvmUserDao, KvmUser> implements IKvmUserService {

    @Autowired
    private KvmUserDao userDao;

    @Override
    public Integer teamAllUserNum(String userCode) {
        List<KvmUser> list = userDao.selectList(new EntityWrapper<KvmUser>().eq("poll_code", userCode));

        return teamAllUserNum(list);
    }

    private Integer teamAllUserNum(List<KvmUser> list) {
        Integer num = list.size();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                KvmUser user = list.get(i);
                num += teamAllUserNum(userDao.selectList(new EntityWrapper<KvmUser>().eq("poll_code", user.getUserCode())));
            }
        }
        return num;
    }

    @Override
    public List<UserNode> teamZtree(String userCode) {
        if (CharUtil.isEmpty(userCode)) {
            userCode = Constant.sysPollCode;
        }
        List<KvmUser> userList = userDao.teamZtree(userCode);
        return createZtreeNode(userList);
    }

    private List<UserNode> createZtreeNode(List<KvmUser> userList) {
        List<UserNode> nodes = new ArrayList<>();
        if (userList.size() > 0) {
            for (int i = 0; i < userList.size(); i++) {
                KvmUser per = userList.get(i);
                UserNode node = new UserNode();
                node.setId(per.getId());
                node.setUserCode(per.getUserCode());
                node.setPollCode(per.getPollCode());
                String tel = per.getUserCode();
                if (CharUtil.isNotEmpty(per.getName())) {
                    node.setName(tel + "(<span style='color:red'>" + per.getName() + "</span>)");
                } else {
                    node.setName(tel + "(<span style='color:red'>" + per.getUserName() + "</span>))");
                }
                // 2.动态加载子类，不查询出子类
                int childrenCount = userDao
                        .selectCount(new EntityWrapper<KvmUser>().eq("poll_code", per.getUserCode()));
                if (childrenCount > 0) {
                    node.setIsParent("true");
                }
                node.setChilCount(childrenCount);
                nodes.add(node);
            }
        }
        return nodes;
    }
}
